﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;
using Components;
using System.IO;
using Meeting.Public;

namespace Meeting.Web.ashx
{
    /// <summary>
    /// TopicPlateHandler 的摘要说明
    /// </summary>
    public class TopicPlateHandler : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            string MeetingId = context.Request["MeetingId"];//原来是给会议传文档，现在思路是给议题上传文档，所以这个id作为议题id
            string TopicId = context.Request["tId"];
            string[] strs = TopicId.Split('|');
            TopicId = strs[0];
            MeetingId = strs[1];
            HttpPostedFile postedFile = context.Request.Files["Filedata"];
            string uploadPath = context.Server.MapPath("~/" + ConfigurationManager.AppSettings["UploadPath"] + "/plate");
            if (postedFile != null)
            {
                Guid plateId = Guid.NewGuid();

                string fullName = postedFile.FileName;
                //获取文件后缀名
                string extension = fullName.Substring(fullName.LastIndexOf("."), (fullName.Length - fullName.LastIndexOf("."))).ToLower();
                //按年月生成文件夹
                string dateFolder = StrHelp.MakeFolderName();
                //拼接上传路径
                uploadPath = uploadPath + "/" + dateFolder + "/" + TopicId.ToString();
                if (!Directory.Exists(uploadPath))
                {
                    Directory.CreateDirectory(uploadPath);
                }
                string filePath = uploadPath + "/" + plateId + extension;
                postedFile.SaveAs(filePath);



                //文件保存成功之后，在数据库中插入一条记录
                Model.TopicPlate model = new Model.TopicPlate();
                model.Comment = "";
                model.IsActive = true;
                model.Id = plateId;
                model.Name = fullName.Replace(extension, "");
                model.UploadDate = DateTime.Now;
                model.TopicId = new Guid(TopicId);
                model.Path = dateFolder;
                model.Format = extension.Replace(".", "");
                model.MeetingId = CommonFunction.varToIntDef(MeetingId, 0);

                //信息写入数据库
                Meeting.BLL.TopicBLL bll = new Meeting.BLL.TopicBLL();
                context.Response.Write(bll.AddPlate(model, true));
                //FileDeepProcess(string.Format("{0}{1}\\{2}", uploadPath, folderName, fileName));
                //下面这句代码缺少的话，上传成功后上传队列的显示不会自动消失
                //context.Response.Write(string.Format("{0}/{1}", filePath, fullName));
            }
            else
            {
                context.Response.Write("0");
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}